package br.com.seosoft.simplecalcfinan;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;
import br.com.seosoft.simplecalcfinan.adapters.ListaAdapter;
import br.com.seosoft.simplecalcfinan.bancoDados.BancoDados;
import br.com.seosoft.simplecalcfinan.utils.ChangeLogDialog;
import br.com.seosoft.simplecalcfinan.utils.IabHelper;
import br.com.seosoft.simplecalcfinan.utils.IabResult;
import br.com.seosoft.simplecalcfinan.utils.Inventory;
import br.com.seosoft.simplecalcfinan.utils.Propaganda;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.Tracker;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.ironsrc.kudoskit.KudosKit;

public class inicial extends ActivyGeral {
	private ListView list;
	private int[] id;
	private String[] descricao;
	private BigDecimal[] saldo_conta;
	private int codigo = 1;
	private AdView adView;
	private Boolean conectado;
	protected int ACTIVITY_CHOOSE_FILE = 2;
	private String filePath;
	private MenuItem enviarCsv, logout;
	private Handler mHandler;
	private IabHelper mHelper;
	private List<String> additionalSkuList = new ArrayList<String>();
	// Your application's package name
	private static final String APP_ID = "br.com.seosoft.simplecalcfinan";
	// The application key from the developer console
	private static final String APP_KEY = "010e6525bf";
	// The names of the in-app items associated with your application
	// You should use an empty array if you don't have in-app items to publish
	private static final String[] INAPP_IDS = new String[] { 
			"retirar.admob" };
	// An array of feature strings; leave empty for now
	private static final String[] FEATURES = new String[] {};
	// The kudosKit object (from package com.ironsrc.kudoskit)
	private KudosKit mKudosKit = null;
	private static boolean EXIBIU_ADS = false;

	private String base64EncodeKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn94gHZw8kWiS7imLc4w0u5GS0a/KXKly8+2SloeblZGjRcgJM9b6TSx1B6vjjXMD10S0AilnN/ZR12SHGjlZqFPl1Bwm/S3gCZFAyVpPXrqydsWwXxa2+kFxCq+FlfCDbPWGALXFAD4ubsJGP/Ytl9iI+sj6hc4Cl7270zGFe0J9Pirfv4UX2jefhpeIdU5uP7JIXS0SRLmY+JTKtraZXDYISAfhRJk6mUdZVmRhJZo56JVpNwfP1pfTCij/mwjWNuO4ejZP8j4mfNVd7n0rpZ/QPAPWbKhnbT2NsGwjz8mIKgUqC5iwGmyUFPeiop2Qqwu7GqXMjk+zUILvXAz+YQIDAQAB";

	// Generate your own 20 random bytes, and put them here.
	private static final byte[] SALT = new byte[] { -46, 65, 30, -128, -103,
			-27, 74, -64, 51, 68, -95, -45, 77, -117, -36, -103, -11, 32, -64,
			89 };

	// preferences
	private SharedPreferences preference;
	private SharedPreferences.Editor editor;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setTitle(R.string.app_name);

		setContentView(R.layout.grupos);

		// mKudosKit = new KudosKit(this, APP_ID, APP_KEY);
		// mKudosKit.setup(FEATURES, INAPP_IDS);
	
//		mKudosKit.debug();
		
		

		// Obtem preferencias salvas
		preference = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());

		editor = preference.edit();

		// Adiciona lista dos itens a comprar
		additionalSkuList.add(ActComprarItens.SKU_RETIRAR_ADMOB);

		// conectado = geral.Conectado(this);

		// BOTOES
		final ImageButton btnNovo = (ImageButton) findViewById(R.id.ibNovo);
		final ImageButton btnCsv = (ImageButton) findViewById(R.id.ibCsv);

		// TEXTO MSG

		// PEGA A LISTA
		list = (ListView) findViewById(R.id.list);
		// list.setAdapter(new ListaAdapter(getApplication(), null));
		// list.setEmptyView(findViewById(R.id.empty));
		registerForContextMenu(list);

		// FUN�� list.setSe

		list.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				String _id = Integer.toString(id[position]);
				String _desc = descricao[position];
				listaContas(_id, _desc, position);
			}
		});

		// Bot��o NOVO
		btnNovo.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				novoRegistro();

			}
		});// fim bot��o NOVO

		// Bot��o CSV
		btnCsv.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				menuCsv();

			}
		});// fim bot��o CSV

		// gera a list view
		// Toast.makeText(this,
		// getString(R.string.InfoMenu),Toast.LENGTH_LONG).show();

		if (Locale.getDefault().toString().equalsIgnoreCase("pt_BR")) {
			ajudaAplicativo();
		}

	}

	private void iniciarIab() {
		try {

			// Inicia service de In-app Billing

			if (mHelper == null) {

				mHelper = new IabHelper(this, base64EncodeKey);
				mHelper.enableDebugLogging(true);

				// Start service das compras
				mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
					public void onIabSetupFinished(IabResult result) {
						if (!result.isSuccess()) {
							// Oh noes, there was a problem.
							Log.d("Iab", "Problem setting up In-app Billing: "
									+ result);
							removerIab();

						} else {
							mHelper.queryInventoryAsync(true,
									additionalSkuList, mQueryFinishedListener);
						}
						// Hooray, IAB is fully set up!
					}
				});
			}

		} catch (Exception e) {
			Log.e("Iab", "Erro ao iniciar IAB: " + e.getMessage());
			removerIab();

		}
	}

	// Listener pare recuperar os itens da google play
	private IabHelper.QueryInventoryFinishedListener mQueryFinishedListener = new IabHelper.QueryInventoryFinishedListener() {

		@Override
		public void onQueryInventoryFinished(IabResult result, Inventory inv) {
			// TODO Auto-generated method stub
			if (result.isFailure()) {
				// handle error

				Log.d("Iab", "Erro ao recuperar lista de itens para comprar ");

				return;
			}

			// Verifica se ja esta compro os itens

			if (!inv.hasPurchase(ActComprarItens.SKU_RETIRAR_ADMOB)) {
				editor.putBoolean(geral.REMOVEU_ADS, false);
				editor.commit();
				Log.v("Iab", "Nao pagou pra remover ");

			} else {
				editor.putBoolean(geral.REMOVEU_ADS, true);
				editor.commit();
				Log.v("Iab", "Pagou pra remover ");
			}

			removerIab();

			try {
				Propaganda propaganda = new Propaganda();

				if (propaganda.verificarClienteJaPago(inicial.this)) {
					EasyTracker.getTracker().sendEvent("Clientes Pagos",
							propaganda.getCliente(), "verificarClientepago",
							null);
				} else {
					mostrarBanner();
				}

			} catch (Exception e) {

				Log.v(geral.LogCat,
						"**** Verificar CLiente erro " + e.getMessage());
				Tracker myTracker = EasyTracker.getTracker(); // Get a reference
																// to
																// tracker.
				myTracker.sendException(e.getMessage(), false); // false
																// indicates
																// non-fatal
																// exception.
			}

		}
	};

	// Envia os dados de analitycs para a google;
	public void enviarEventobanco() {

		if (preference.getBoolean("ITAU", false)) {

			Tracker tracker = EasyTracker.getTracker();
			tracker.sendEvent("Receber SMS", "ITAU", "SMS inserido no banco",
					null);
			editor.putBoolean("ITAU", false);
			editor.commit();

		}
		if (preference.getBoolean("CAIXA", false)) {
			Tracker tracker = EasyTracker.getTracker();
			tracker.sendEvent("Receber SMS", "CAIXA", "SMS inserido no banco",
					null);
			editor.putBoolean("CAIXA", false);
			editor.commit();
		}
		if (preference.getBoolean("BRADESCO", false)) {
			Tracker tracker = EasyTracker.getTracker();
			tracker.sendEvent("Receber SMS", "BRADESCO",
					"SMS inserido no banco", null);
			editor.putBoolean("CAIXA", false);
			editor.commit();
		}
		if (preference.getBoolean("BRASIL", false)) {
			Tracker tracker = EasyTracker.getTracker();
			tracker.sendEvent("Receber SMS", "BRASIL", "SMS inserido no banco",
					null);
			editor.putBoolean("BRASIL", false);
			editor.commit();
		}
		if (preference.getBoolean("DINERS", false)) {
			Tracker tracker = EasyTracker.getTracker();
			tracker.sendEvent("Receber SMS", "DINERS", "SMS inserido no banco",
					null);
			editor.putBoolean("DINERS", false);
			editor.commit();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub

		getSupportMenuInflater().inflate(R.menu.menu, menu);

		if (VERSION.SDK_INT >= 14) {
			menu.findItem(R.id.menuImportarSms).setVisible(true);

		}
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();

	}

	//

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub

		enviarCsv = (MenuItem) menu.findItem(R.id.menuEnviarCsv);
		enviarCsv.setVisible(true);

		logout = (MenuItem) menu.findItem(R.id.menuSair);

		if (geral.logado == true) {
			logout.setVisible(true);
		}

		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {

		case R.id.menuRate:

			Uri uri = Uri.parse("market://details?id="
					+ getApplicationContext().getPackageName());
			Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
			startActivity(goToMarket);

			return true;

		case R.id.menuEnviarCsv:

			Intent shareIntent = new Intent();
			shareIntent.setAction(Intent.ACTION_SEND);

			shareIntent.putExtra(Intent.EXTRA_STREAM,
					Uri.fromFile(new File(exportCsv(true))));
			shareIntent.setType("text/comma-separated-values");
			startActivity(Intent.createChooser(shareIntent, getResources()
					.getText(R.string.enviarCsv) + "..."));

			return true;

		case R.id.meuNovidades:

			novidades();

			return true;

		case R.id.menuConfig:

			startActivityForResult(new Intent(getApplicationContext(),
					Config.class), codigo);

			return true;

		case R.id.menuSair:

			geral.logado = false;

			android.os.Process.killProcess(android.os.Process.myPid());
			return true;

		}
		return super.onOptionsItemSelected(item);
	}

	// FU����O AdMob Google e RevMob
	public void mostrarBanner() {

		if (!preference.getBoolean(geral.REMOVEU_ADS, true)) {

			if (!EXIBIU_ADS) {

				EXIBIU_ADS = true;
			}

			// RevMobBanner banner = revmob.createBanner(this);
			// ViewGroup view = (ViewGroup)
			// findViewById(R.id.BannerListaGrupos);
			// view.addView(banner);

			// // Create the adView
			adView = new AdView(this);
			adView.setAdUnitId(geral.id_AdMob);
			adView.setAdSize(AdSize.BANNER);

			// Lookup your LinearLayout assuming it���s been given
			// the attribute android:id="@+id/mainLayout"
			LinearLayout layout = (LinearLayout) findViewById(R.id.BannerListaGrupos);

			layout.removeAllViewsInLayout();

			// Add the adView to it
			layout.addView(adView);

			// Initiate a generic request to load it with an ad
			AdRequest request = new AdRequest.Builder().build();

			// request.addTestDevice(AdRequest.TEST_EMULATOR);// Emulador
			// request.addTestDevice("emulator-5554");// Testar dispositivo
			// Android
			adView.loadAd(request);

		}

	}

	// MOSTRAR NOTIFICA��AO

	public void notificacao(String titulo, String descricao, int drawable) {

		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
				this).setSmallIcon(drawable).setContentTitle(titulo)
				.setContentText(descricao);

		Intent chooseFile;
		Intent intent;
		chooseFile = new Intent(Intent.ACTION_GET_CONTENT);

		chooseFile.setType("text/comma-separated-values");
		intent = Intent.createChooser(chooseFile,
				getResources().getString(R.string.abrirCsvCom));

		TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
		// Adds the back stack for the Intent (but not the Intent itself)
		stackBuilder.addParentStack(inicial.class);
		// Adds the Intent that starts the Activity to the top of the stack
		stackBuilder.addNextIntent(intent);
		PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
				PendingIntent.FLAG_UPDATE_CURRENT);
		mBuilder.setContentIntent(resultPendingIntent);
		NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		int mId = 4566666;
		// mId allows you to update the notification later on.
		mNotificationManager.notify(mId, mBuilder.build());
	}

	// FUN����O LISTA GRUPOS

	public void ListarGrupos() {

		new ListarGruposThread().execute("");

	}

	public void toggleProgressBar() {

		LinearLayout layoutVazio = (LinearLayout) findViewById(R.id.layoutVazioPasta);
		ProgressBar progress = (ProgressBar) findViewById(R.id.pbPasta);

		if (layoutVazio.getVisibility() == View.VISIBLE) {
			layoutVazio.setVisibility(View.GONE);
			progress.setVisibility(View.GONE);
			list.setVisibility(View.VISIBLE);
		} else {
			layoutVazio.setVisibility(View.VISIBLE);
			list.setVisibility(View.GONE);
			progress.setVisibility(View.VISIBLE);
		}

	}

	public void toggleListaVazia(Boolean vazio) {

		LinearLayout layoutVazio = (LinearLayout) findViewById(R.id.layoutVazioPasta);
		TextView texto = (TextView) findViewById(R.id.ListaVaziaPasta);

		if (vazio == false) {
			layoutVazio.setVisibility(View.GONE);
			texto.setVisibility(View.GONE);
			list.setVisibility(View.VISIBLE);
		} else {
			layoutVazio.setVisibility(View.VISIBLE);
			list.setVisibility(View.GONE);
			texto.setVisibility(View.VISIBLE);
		}

	}

	class ListarGruposThread extends AsyncTask<String, Void, Void> {

		List<geral> geralList = new ArrayList<geral>();
		double aux = 0;
		double total = 0;
		BigDecimal aux2, total2;
		BancoDados bd;

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();

			total2 = new BigDecimal(0);
			toggleProgressBar();
			bd = new BancoDados(getApplicationContext(), true);

		}

		@Override
		protected Void doInBackground(String... params) {
			// TODO Auto-generated method stub

			bd.BuscaTodosRegistrosGrupos();

			id = new int[bd.TotalRegistroGrupos()];
			descricao = new String[bd.TotalRegistroGrupos()];
			saldo_conta = new BigDecimal[bd.TotalRegistroGrupos()];

			for (int i = 0; i < bd.TotalRegistroGrupos(); i++) {

				bd.ProximoRegistroGrupos();
				// inicia o vetor com o total de registros

				geral geral = new geral();
				geral.setIdGrupo(bd.c.getInt(0));
				geral.setDescGrupo(bd.c.getString(1));
				geral.setTotalContasGrupo(bd.c.getDouble(2));

				geralList.add(geral);

				id[i] = geral.getIdGrupo();
				descricao[i] = geral.getDescGrupo();
				saldo_conta[i] = new BigDecimal(bd.c.getString(2));

				aux2 = new BigDecimal(bd.c.getString(2));
				total2 = total2.add(aux2);
				// Adiciona cada valor e soma o total
				aux = Double.valueOf(geral.getTotalContasGrupo());
				total = aux + total;
				Log.e(br.com.seosoft.simplecalcfinan.geral.LogCat, "Aux: "
						+ aux2);
				Log.e(br.com.seosoft.simplecalcfinan.geral.LogCat, "Total: "
						+ total2);
			}

			// Corrige as data lançadas com erro
			try {
				bd.corrigirDatas();
			} catch (Exception e) {
				// TODO: handle exception
				Tracker myTracker = EasyTracker.getTracker(); // Get a reference
																// to
				// tracker.
				myTracker.sendException(e.getMessage(), true); // false
																// indicates
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			// Valor Total DOS GRUPOS no Text View

			geral geral = new geral();

			TextView tvTotal = (TextView) findViewById(R.id.TotalGrupo);
			tvTotal.setText(geral.DecimalCurrency(total2.doubleValue()));
			tvTotal.setTextColor(geral.mudarCor(total2.doubleValue()));

			// FECHA O BANCO DE DADOS
			ListaAdapter adapter = new ListaAdapter(getApplicationContext(),
					geralList);

			list.setAdapter(adapter);

			bd.fechar();
			toggleProgressBar();
			if (adapter.isEmpty()) {
				// toggleListaVazia(true);
			}

		}

	}

	// EXPORTA CSV
	public String exportCsv(Boolean tmp) {

		final BancoDados bd = new BancoDados(this, true);

		CSVWriter writer = null;
		String caminho = Environment.getExternalStorageDirectory()
				+ "/Simple Calc Finan Dados/";

		EasyTracker.getTracker().sendEvent("Acoes", "Exportado CSV",
				"exportCsv", null);

		if (tmp == true) {

			File file = new File(caminho);
			file.getParentFile().mkdirs();
			file.mkdirs();

			String arquivo = "tmp_dados" + ".csv";

			caminho = Environment.getExternalStorageDirectory()
					+ "/Simple Calc Finan Dados/" + arquivo;
			file.getParentFile().mkdirs();
			file.mkdirs();

		} else {

			SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy/MM/dd/");

			String pastas = simpleFormat.format(new Date(System
					.currentTimeMillis()));

			caminho = Environment.getExternalStorageDirectory()
					.getAbsolutePath() + "/Simple Calc Finan Dados/" + pastas;

			File file = new File(caminho);
			file.mkdirs();
		}

		try {

			if (tmp == false) {

				SimpleDateFormat simpleFormat2 = new SimpleDateFormat("H-m-s");

				String arquivo = simpleFormat2.format(new Date(System
						.currentTimeMillis()));

				caminho = caminho + arquivo + ".csv";
			}

			Log.v(geral.LogCat, " URI: " + caminho);

			writer = new CSVWriter(new FileWriter(caminho), ',');

			bd.BuscaTodosRegistrosGruposContas();

			String[] colunas = { "GRUPO", "CONTA", "SALDO", "DATA" };
			writer.writeNext(colunas);

			for (int i = 0; i < bd.TotalRegistroGruposContas(); i++) {

				bd.ProximoRegistroContasGrupos();

				if (bd.c.getString(1) != null) {

					String[] valores = { bd.c.getString(0), bd.c.getString(1),
							bd.c.getString(2), bd.c.getString(3) };
					writer.writeNext(valores);

				} else {

					String[] valores = { bd.c.getString(0), "Exemplo", "45",
							"10/06/2013 13:12:00" };
					writer.writeNext(valores);
				}

			}
			writer.close();
			Log.e(geral.LogCat, "CSV CRIADO" + caminho);
			bd.fechar();

			// EXIBIR DIALOGO ONDE O CSV FOI SALVO

			if (tmp == false) {

				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setMessage(caminho);

				builder.setTitle(getResources().getString(R.string.CsvSalvo));
				builder.setIcon(android.R.drawable.ic_dialog_info);

				builder.setNeutralButton(android.R.string.ok,
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog, int id) {

								dialog.cancel();

							}
						});

				AlertDialog alertDialog = builder.create();
				alertDialog.show();
			}

			// Toast.makeText(inicial.this,getResources().getString(R.string.CsvSalvo)+" "+caminho+"",
			// Toast.LENGTH_LONG).show();

		} catch (IOException e) {

			Log.e(geral.LogCat, "ERRO AO CRIAR CSV: " + e.getMessage());
			Toast.makeText(
					inicial.this,
					getResources().getString(R.string.erroCsv) + e.getMessage(),
					Toast.LENGTH_LONG).show();

			Tracker myTracker = EasyTracker.getTracker(); // Get a reference to
			// tracker.
			myTracker.sendException(e.getMessage(), true); // false indicates
			// non-fatal
			// exception.

		}
		return caminho;
	}

	// EXPORTA CSV
	public String exportPastaCsv(Boolean tmp, String pasta, String id_grupo) {

		EasyTracker.getTracker().sendEvent("Acoes", "Exportado Pasta CSV",
				"exportPastaCsv", null);
		final BancoDados bd = new BancoDados(this, true);

		CSVWriter writer = null;
		String caminho = Environment.getExternalStorageDirectory()
				+ "/Simple Calc Finan Dados/";

		if (tmp == true) {

			File file = new File(caminho);
			file.getParentFile().mkdirs();

			String arquivo = "tmp_dados.csv";

			caminho = Environment.getExternalStorageDirectory()
					+ "/Simple Calc Finan Dados/" + arquivo;

		} else {

			SimpleDateFormat simpleFormat = new SimpleDateFormat("/yyyy/MM/dd/");

			String pastas = simpleFormat.format(new Date(System
					.currentTimeMillis()));

			caminho = Environment.getExternalStorageDirectory()
					.getAbsolutePath()
					+ "/Simple Calc Finan Dados/"
					+ pasta.trim() + pastas;

			File file = new File(caminho);
			file.mkdirs();
		}

		try {

			if (tmp == false) {

				SimpleDateFormat simpleFormat2 = new SimpleDateFormat("H-m-s");

				String arquivo = simpleFormat2.format(new Date(System
						.currentTimeMillis()));

				caminho = caminho + arquivo + ".csv";
			}

			Log.v(geral.LogCat, " URI: " + caminho);

			writer = new CSVWriter(new FileWriter(caminho), ',');

			bd.BuscaTodosRegistrosContas(id_grupo, 0, 0);

			String[] colunas = { "GRUPO", "CONTA", "SALDO", "DATA" };
			writer.writeNext(colunas);

			for (int i = 0; i < bd.TotalRegistroContas(); i++) {

				bd.ProximoRegistroContas();

				if (bd.c.getCount() > 0) {

					String[] valores = { pasta, bd.c.getString(2),
							bd.c.getString(3), bd.c.getString(4) };

					writer.writeNext(valores);

				} else {

					String[] valores = { pasta, "Exemplo", "45",
							"20/06/2013 13:23:00" };
					writer.writeNext(valores);
				}

			}
			writer.close();
			Log.e(geral.LogCat, "CSV CRIADO" + caminho);
			bd.fechar();

			// EXIBIR DIALOGO ONDE O CSV FOI SALVO

			if (tmp == false) {

				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setMessage(caminho);

				builder.setTitle(getResources().getString(R.string.CsvSalvo));
				builder.setIcon(android.R.drawable.ic_dialog_info);

				builder.setNeutralButton(android.R.string.ok,
						new DialogInterface.OnClickListener() {

							public void onClick(DialogInterface dialog, int id) {

								dialog.cancel();

							}
						});

				AlertDialog alertDialog = builder.create();
				alertDialog.show();
			}

			// Toast.makeText(inicial.this,getResources().getString(R.string.CsvSalvo)+" "+caminho+"",
			// Toast.LENGTH_LONG).show();

		} catch (IOException e) {

			Log.e(geral.LogCat, "ERRO AO CRIAR CSV: " + e.getMessage());
			Toast.makeText(inicial.this, R.string.erroCsv, Toast.LENGTH_SHORT)
					.show();

			Tracker myTracker = EasyTracker.getTracker(); // Get a reference to
			// tracker.
			myTracker.sendException(e.getMessage(), false); // false indicates
			// non-fatal
			// exception.

		}
		return caminho;
	}

	// MENU IMPORTAR CSV

	public void menuImportarCsv() {

		// tEasyTracker.getInstance().setContext(this);

		// Registra o Alert Dialog
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(R.string.alertaImportarCsv);
		builder.setTitle(android.R.string.dialog_alert_title);
		builder.setIcon(android.R.drawable.ic_dialog_alert);
		builder.setCancelable(true);

		EasyTracker.getTracker().sendEvent("Dialogos",
				"dialogo exibir menu importar CSV", "menuImportarCsv", null);
		builder.setPositiveButton(R.string.sim,
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int id) {

						EasyTracker.getTracker().sendEvent("Dialogos",
								"dialogo click em SIM importar CSV",
								"menuImportarCsv click SIM", null);

						Intent chooseFile;
						Intent intent;
						chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
						chooseFile.setType("text/plain");
						intent = Intent.createChooser(chooseFile,
								getResources().getString(R.string.abrirCsvCom));
						startActivityForResult(intent, ACTIVITY_CHOOSE_FILE);

					}
				});

		builder.setNegativeButton(R.string.nao,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

						dialog.cancel();
					}
				});

		AlertDialog alertDialog = builder.create();
		alertDialog.show();

	}

	public void ajudaAplicativo() {

		preference = PreferenceManager
				.getDefaultSharedPreferences(inicial.this);

		if (preference.getBoolean("mostrarAjuda", true)) {

			View view = getLayoutInflater().inflate(R.layout.dialogo_ajuda_app,
					null);

			final CheckBox cbMostrarNovamente = (CheckBox) view
					.findViewById(R.id.cbMostrarAjuda);

			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle(R.string.tituloAjuda);
			builder.setIcon(android.R.drawable.ic_dialog_info);

			builder.setNeutralButton(getResources().getString(R.string.config),
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub

							startActivityForResult(new Intent(
									getApplicationContext(), Config.class),
									codigo);

						}
					});

			builder.setPositiveButton("OK",
					new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub

							SharedPreferences.Editor editor;
							preference = PreferenceManager
									.getDefaultSharedPreferences(getApplicationContext());
							editor = preference.edit();

							if (cbMostrarNovamente.isChecked()) {
								editor.putBoolean("mostrarAjuda", false);
								editor.commit();

							} else {
								editor.putBoolean("mostrarAjuda", true);
								editor.commit();
							}

						}
					});

			AlertDialog alertDialog = builder.create();
			alertDialog.setView(view);

			alertDialog.show();
		}

	}

	protected void dialogUsuarioPago() {

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Pagamento do App");
		builder.setIcon(android.R.drawable.ic_dialog_info);
		builder.setNeutralButton("OK", null);
		builder.setMessage("Pago");
		AlertDialog alertDialog = builder.create();

		alertDialog.show();
	}

	// FUN����O ABRE MENU IMPORTA OU EXPORTA CSV
	public void menuCsv() {

		// Registra o Alert Dialog
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(R.string.ImportExportCSV);
		builder.setCancelable(true);

		builder.setPositiveButton(R.string.importar,
				new DialogInterface.OnClickListener() {

					public void onClick(DialogInterface dialog, int id) {

						menuImportarCsv();

					}
				});

		builder.setNegativeButton(R.string.export,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

						exportCsv(false);
					}
				});

		AlertDialog alertDialog = builder.create();
		alertDialog.show();

	}

	// Fun����es para cria o menu de contexto

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle(R.string.Opcoes);
		// menu.add(0, 0, 0, ">>Abrir Contas do grupo");

		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;

		if (descricao[info.position].equalsIgnoreCase("SMS.BANCOS")) {
			menu.add(0, 1, 0, R.string.editar).setEnabled(false);
		} else {
			menu.add(0, 1, 0, R.string.editar);
		}

		menu.add(0, 2, 0, R.string.Excluir);
		menu.add(0, 3, 0, R.string.export);
		menu.add(0, 4, 0, R.string.enviarPasta);
		menu.add(0, 5, 0, R.string.cancel);
	}

	// fun����o para dar a����o a cada op����o do menu

	@Override
	public boolean onContextItemSelected(android.view.MenuItem item) {
		// TODO Auto-generated method stub
		final BancoDados bd = new BancoDados(this, false);

		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		final String _id = Integer.toString(id[info.position]);
		String _desc = descricao[info.position];
		BigDecimal _valor = saldo_conta[info.position];

		// Registra o Alert Dialog
		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setMessage(getResources().getString(R.string.Excluir) + " "
				+ _desc + " ?");
		builder.setCancelable(false);

		builder.setPositiveButton(R.string.sim,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// put your code here
						bd.DeletarRegistroGrupos(_id);

						ListarGrupos();

					}
				});
		builder.setNegativeButton(R.string.nao,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// put your code here
						dialog.cancel();
					}
				});
		AlertDialog alertDialog = builder.create();

		Log.e(geral.LogCat, "Item selecinado: " + item.getItemId()
				+ " Lista selecionada: " + info.position + ": "
				+ id[info.position]);

		switch (item.getItemId()) {

		case 0:
			listaContas(_id, _desc, info.position);
			break;
		case 1:
			editarRegistro(_id, _desc, _valor);

			break;
		case 2:
			alertDialog.show();
			break;

		case 3:
			exportPastaCsv(false, _desc, _id);
			break;

		case 4:

			Intent shareIntent = new Intent();
			shareIntent.setAction(Intent.ACTION_SEND);

			shareIntent.putExtra(Intent.EXTRA_STREAM,
					Uri.fromFile(new File(exportPastaCsv(true, _desc, _id))));
			shareIntent.setType("text/comma-separated-values");
			startActivity(Intent.createChooser(shareIntent, getResources()
					.getText(R.string.enviarCsv) + " '" + _desc + "'"));
			break;

		default:

			break;
		}
		return true;
	}

	// VAI PARA A LISTAGEM DE CONTAS

	public void listaContas(String id, String descGrupo, int position) {

		final Intent itContas = new Intent(this, contas.class);
		itContas.putExtra("fk_grupo", id);
		itContas.putExtra("desc_grupo", descGrupo);
		itContas.putExtra("position_pasta", String.valueOf(position));
		startActivityForResult(itContas, codigo);

	}

	// ADICIONA NOVO GRUPO
	public void novoRegistro() {

		final Intent itGrupos = new Intent(this, Ed_Grupos.class);
		itGrupos.putExtra("acao", "novo");
		startActivityForResult(itGrupos, codigo);
	}

	// EDITAR REGISTRO GRUPO
	public void editarRegistro(String id, String desc, BigDecimal _valor) {
		final Intent itGrupos = new Intent(this, Ed_Grupos.class);
		itGrupos.putExtra("acao", "editar");
		itGrupos.putExtra("id_grupo", id);
		itGrupos.putExtra("descricao_grupo", desc);
		itGrupos.putExtra("saldo_conta", _valor.toString());
		startActivityForResult(itGrupos, codigo);
	}

	// recebe resultado intents

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		Log.e("log", "Intent pick: ");
		if (codigo == requestCode) {
			Bundle params = data != null ? data.getExtras() : null;
			if (params != null) {
				String atualizar = params.getString("atualizar");
				if (resultCode == 1) {
					// Sim
					if (atualizar.equals("sim")) {
						// Toast.makeText(this, R.string.atualizarLista,
						// Toast.LENGTH_SHORT).show();

						ListarGrupos();
						// Toast.makeText(this,
						// getString(R.string.InfoMenu),Toast.LENGTH_LONG).show();
					}
				}
			}
		}
		if (requestCode == ACTIVITY_CHOOSE_FILE) {

			if (resultCode == RESULT_OK) {
				Uri uri = data.getData();
				filePath = uri.getPath();

				PogressdialogCsv(filePath);

			}

		}
	}

	// FAZ A BARRA DE PROGRESSO PARA LEITURA DO CSV
	public void PogressdialogCsv(String caminho) {
		new PogressdialogCsv().execute(caminho);
	}

	// MENU NOVIDADES ALERT DIALOG

	public void novidades() {

		// AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// // Get the layout inflater
		// LayoutInflater inflater = getLayoutInflater();
		//
		// builder.setCancelable(false);
		// builder.setTitle(R.string.novidades);
		//
		// // Inflate and set the layout for the dialog
		// // Pass null as the parent view because its going in the dialog
		// layout
		// builder.setView(inflater.inflate(R.layout.novidades, null))
		// // Add action buttons
		// .setNeutralButton(android.R.string.ok,
		// new DialogInterface.OnClickListener() {
		// @Override
		// public void onClick(DialogInterface dialog, int id) {
		// // sign in the user ...
		// dialog.dismiss();
		// }
		// });
		//
		// AlertDialog dialog = builder.create();
		// dialog.show();
		EasyTracker.getTracker().sendEvent("Dialogos", "Novidades exibido",
				"novidades", null);
		ChangeLogDialog changeLog = new ChangeLogDialog(this);
		changeLog.show();

	}

	class PogressdialogCsv extends

	AsyncTask<String, Void, Void> {

		String error;
		private ProgressDialog progressDialog;

		@Override
		protected void onPreExecute() {

			progressDialog = new ProgressDialog(inicial.this);

			progressDialog.setMessage(getResources().getString(
					R.string.carregandoArquivo));

			progressDialog.show();

		}

		@Override
		protected Void doInBackground(String... caminho) {

			try {

				CSVReader reader = new CSVReader(new FileReader(caminho[0]));
				String[] nextLine;
				String grupo = " ";

				int fk_grupo = 0;

				nextLine = reader.readNext();// PULA 1 LINHA .NOME COLUNA

				if (nextLine.length >= 4) {

					BancoDados bd = new BancoDados(inicial.this, false);

					// bd.db.execSQL("DELETE FROM [grupos]");
					// bd.db.execSQL("DELETE FROM [contas]");
					bd.deletaBancoDados();
					bd.recriarBancoDados();

					while ((nextLine = reader.readNext()) != null) {

						if (!nextLine[0].equals(grupo) || grupo == " ") {

							++fk_grupo;

							bd.db.execSQL("INSERT INTO [grupos] ([desc]) VALUES ('"
									+ nextLine[0] + "');");

							Log.v(geral.LogCat, "IMPORT CSV GRUPO: "
									+ nextLine[0]);

							grupo = nextLine[0];

							Log.v(geral.LogCat, "IMPORT CSV FK_GRUPO "
									+ fk_grupo);

						}

						if (nextLine[1] != "") {

							Log.v(geral.LogCat, "IMPORT CSV CONTA: "
									+ nextLine[1]);
							Log.v(geral.LogCat, "IMPORT CSV SALDO: "
									+ nextLine[2]);
							Log.v(geral.LogCat, "IMPORT CSV DATA: "
									+ nextLine[3]);

							bd.db.execSQL("INSERT INTO [contas] ([desc],[fk_grupo],[saldo],[data_time]) VALUES ('"
									+ nextLine[1]
									+ "',"
									+ fk_grupo
									+ ","
									+ nextLine[2] + ",'" + nextLine[3] + "');");

						}

					}
					reader.close();
					bd.fechar();

				} else {

					if (nextLine.length >= 3) {

						BancoDados bd = new BancoDados(inicial.this, false);

						// bd.db.execSQL("DELETE FROM [grupos]");
						// bd.db.execSQL("DELETE FROM [contas]");
						bd.deletaBancoDados();
						bd.recriarBancoDados();

						while ((nextLine = reader.readNext()) != null) {

							if (!nextLine[0].equals(grupo) || grupo == " ") {

								++fk_grupo;

								bd.db.execSQL("INSERT INTO [grupos] ([desc]) VALUES ('"
										+ nextLine[0] + "');");

								Log.v(geral.LogCat, "IMPORT CSV GRUPO: "
										+ nextLine[0]);

								grupo = nextLine[0];

								Log.v(geral.LogCat, "IMPORT CSV FK_GRUPO "
										+ fk_grupo);

							}

							if (nextLine[1] != "") {

								Log.v(geral.LogCat, "IMPORT CSV CONTA: "
										+ nextLine[1]);
								Log.v(geral.LogCat, "IMPORT CSV SALDO: "
										+ nextLine[2]);

								bd.db.execSQL("INSERT INTO [contas] ([desc],[fk_grupo],[saldo]) VALUES ('"
										+ nextLine[1]
										+ "',"
										+ fk_grupo
										+ ","
										+ nextLine[2] + ");");

							}

						}
						reader.close();
						bd.fechar();

					} else {
						error = "Erro CSV";
					}

				}
			} catch (Exception e) {
				// TODO Auto-generated catch block

				error = e.getMessage();
				Log.e(geral.LogCat,
						"IMPORT CSV ERROR AO LER LINHAS: " + e.getMessage());
				Tracker myTracker = EasyTracker.getTracker(); // Get a reference
																// to
				// tracker.
				myTracker.sendException(e.getMessage(), false); // false
																// indicates
				// non-fatal
				// exception.
			}

			// Corrigir datas importadas com erro

			editor.putBoolean("corrigirData", true).commit();

			new BancoDados(getApplicationContext(), false).corrigirDatas();

			return null;

		}

		@Override
		protected void onPostExecute(Void result) {

			progressDialog.dismiss();

			ListarGrupos();

			if (error != null) {

				Toast.makeText(inicial.this, R.string.csvInvalido,
						Toast.LENGTH_SHORT).show();

			}
		}

	}

	public void removerIab() {
		if (mHelper != null)

			try {
				mHelper.dispose();
			} catch (Exception e) {
				// TODO: handle exception
			}

		mHelper = null;
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
//		mKudosKit.onStart();
//		mKudosKit.startRightspot("Open App");
		// enviar dados para google
		enviarEventobanco();

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub

		ListarGrupos();
		super.onResume();

		// Starting RevMob session
		// revmob = RevMob.start(this, geral.REVMOB_APP_ID);
		// VERIFICA SE CLIENTE JA COMPROU O PCAOTE PARA REMOVER OS ADS
		iniciarIab();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
//		mKudosKit.onStop();
	}

	@Override
	protected void onDestroy() {

		if (adView != null) {
			adView.destroy();
		}
		EXIBIU_ADS = false;
//		mKudosKit.onDestroy();
		super.onDestroy();
		removerIab();

	}

};
